/*
COPYRIGHT (C) 2008 EPISERVER AB

THIS FILE IS PART OF WIKIX.
WIKIX IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

WIKIX IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER GENERAL PUBLIC LICENSE FOR MORE DETAILS.
YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH WIKIX. IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Web.WebControls;
using EPiServer.Filters;
using EPiServer.Research.Wiki.DynamicContent;
using System.Xml;
using EPiServer.Core.Html;
using EPiServer.Web;


namespace EPiServer.Research.Wiki.Units
{
    public partial class Feed : WikiElement
    {
        #region Member variables
        private string _baseUrl = string.Empty;
        #endregion
        #region Properties
        /// <summary>
        /// Gets the base URL.
        /// </summary>
        /// <value>The base URL.</value>
        private string baseUrl
        {
            get
            {
                if (_baseUrl == String.Empty)
                {
                    _baseUrl = CreateExternalLink(CurrentPage);
                    string separator = "?";
                    if (_baseUrl.Contains(separator))
                        _baseUrl += "&";
                    else
                        _baseUrl += "?";
                }
                return _baseUrl;
            }
        }
        /// <summary>
        /// Gets the RSS link.
        /// </summary>
        /// <value>The RSS link.</value>
        public string RSSLink
        {
            get
            {
                return baseUrl + "feed=RSS";
            }
        }

        /// <summary>
        /// Gets the ATOM link.
        /// </summary>
        /// <value>The ATOM link.</value>
        public string ATOMLink
        {
            get
            {
                return baseUrl + "feed=ATOM";
            }
        }
       

        protected PageDataCollection FeedSource
        {
            get
            {
                
                return GetFeedPages();
                //return Filters.FilterForVisitor.Filter(DataFactory.Instance.GetChildren(CurrentPage.PageLink));
            }
        }
        #endregion

        #region Private Methods
        private PageDataCollection GetFeedPages()
        {
            PageDataCollection pages = new PageDataCollection();
            pages.Add(DataFactory.Instance.GetChildren(CurrentPage.PageLink));
            pages.Add(CurrentPage);
            return Filters.FilterForVisitor.Filter(pages);
        }
        #endregion

        protected override void OnLoad(EventArgs e)
        {
            HtmlLink link = new HtmlLink();
            string url = CreateExternalLink(CurrentPage);
            string separator = "?";

            if (url.Contains("?"))
            {
                separator = "&";
            }

            link.Href = String.Format("{0}{1}feed=RSS", url, separator);
            link.Attributes.Add("rel", "alternate");
            link.Attributes.Add("type", "application/rss+xml");
            link.Attributes.Add("title", String.Format("RSS {0} ", CurrentPage.PageName));
            Page.Header.Controls.Add(link);

            link = new HtmlLink();
            link.Href = String.Format("{0}{1}feed=Atom", url, separator);
            link.Attributes.Add("rel", "alternate");
            link.Attributes.Add("type", "application/atom+xml");
            link.Attributes.Add("title", String.Format("Atom {0} ", CurrentPage.PageName));
            Page.Header.Controls.Add(link);

                base.OnLoad(e);
        }



        /// <summary>
        /// Gets the feed count property.
        /// </summary>
        /// <value>The amount of items listed in the feed. Can be overridden by a page/dynamic property.</value>
        private int FeedCount
        {
            get
            {
                return Int32.MaxValue;
            }
        }

 

        #region method overrides
        /// <summary>
        /// Checks the query string for a feed parameter. If the feed prameter equals "RSS" we generate an RSS 2.0 feed instead of the normal display.
        /// If the feed equals "Atom" we generate a Atom 1.0 feed instead of the normal display.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
        
        /// 

        protected override void OnInit(EventArgs e)
        {
     
            if (String.Compare(Request["feed"], "RSS", true) == 0)
            {
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.ContentType = "text/xml";
                WriteRSS();
                Response.End();
            }
            else if (String.Compare(Request["feed"], "Atom", true) == 0)
            {
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.ContentType = "text/xml";
                WriteAtom();
                Response.End();
            }

            base.OnInit(e);
        }


        /// <summary>
        /// Writes the RSS feed.
        /// </summary>
        protected virtual void WriteRSS()
        {
            XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8);
            string url;
            PageData page;

            writer.WriteStartDocument();
            writer.WriteStartElement("rss");
            writer.WriteAttributeString("version", "2.0");
            writer.WriteAttributeString("xmlns:dc", "http://purl.org/dc/elements/1.1/");
            writer.WriteStartElement("channel");
            writer.WriteElementString("language", CurrentPage.LanguageID);
            writer.WriteElementString("title", CurrentPage.PageName);

            writer.WriteElementString("link", EPiServer.Configuration.Settings.Instance.SiteUrl.ToString());
            writer.WriteElementString("description", CurrentPage["Description"] as string);
            writer.WriteElementString("ttl", "60");
            writer.WriteElementString("generator", "EPiServer Wiki");

            for (int i = 0; i < FeedSource.Count && i < FeedCount; i++)
            {
                page = FeedSource[i];
                url = CreateExternalLink(page);
                writer.WriteStartElement("item");
                writer.WriteElementString("title", page.PageName);
                writer.WriteElementString("link", url);

                writer.WriteElementString("description", TextIndexer.StripHtml((String)page["MainBody"], 250));
                writer.WriteElementString("guid", url);
                writer.WriteElementString("pubDate", page.Changed.ToString("r"));

                foreach (int category in page.Category)
                {
                    writer.WriteElementString("category", page.Category.GetCategoryName(category));
                }
                writer.WriteEndElement();
            }

            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndDocument();

            writer.Close();
        }

        /// <summary>
        /// Writes the atom feed.
        /// </summary>
        protected virtual void WriteAtom()
        {
            XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8);
            string url;
            PageData page;

            writer.WriteStartDocument();
            writer.WriteStartElement("feed");
            writer.WriteAttributeString("xmlns", "http://www.w3.org/2005/Atom");

            writer.WriteStartElement("title");
            writer.WriteAttributeString("type", "text");
            writer.WriteValue(CurrentPage.PageName);
            writer.WriteEndElement();

            writer.WriteStartElement("link");
            writer.WriteAttributeString("href", EPiServer.Configuration.Settings.Instance.SiteUrl.ToString());
            writer.WriteEndElement();

            writer.WriteElementString("updated", DateTime.Now.ToUniversalTime().ToString("o"));
            writer.WriteElementString("id", CreateExternalLink(CurrentPage));

            writer.WriteStartElement("generator");
            writer.WriteAttributeString("uri", EPiServer.Configuration.Settings.Instance.SiteUrl.ToString());
            writer.WriteAttributeString("version", "1.0");
            writer.WriteValue("EPiServer Wiki");
            writer.WriteEndElement();

            for (int i = 0; i < FeedSource.Count && i < FeedCount; i++)
            {
                page = FeedSource[i];
                url = CreateExternalLink(page);
                writer.WriteStartElement("entry");
                writer.WriteElementString("title", page.PageName);

                writer.WriteStartElement("link");
                writer.WriteAttributeString("href", url);
                writer.WriteEndElement();

                writer.WriteElementString("id", url);
                writer.WriteElementString("updated", page.Changed.ToUniversalTime().ToString("o"));

                writer.WriteElementString("summary", TextIndexer.StripHtml((String)page["MainBody"], 250));

                writer.WriteEndElement();
            }

            writer.WriteEndElement();
            writer.WriteEndDocument();

            writer.Close();
        }
        #endregion

        /// <summary>
        /// Create a string with an absolute link to the page. Checks if furl is enabled and rewrites the link if appropriate.
        /// </summary>
        /// <param name="page">A PageData to create an absolute link from.</param>
        /// <returns>An absolute link to page</returns>
        public string CreateExternalLink(PageData page)
        {
            UrlBuilder url = new UrlBuilder(page.LinkURL);

            if (UrlRewriteProvider.IsFurlEnabled && PermanentLinkUtility.IsMappableUrl(url))
            {
                Global.UrlRewriteProvider.ConvertToExternal(url, null, System.Text.UTF8Encoding.UTF8);
                return UriSupport.Combine(EPiServer.Configuration.Settings.Instance.SiteUrl.ToString(), url.ToString());
            }


            return url.ToString();

        }

        protected override string GetAscxUrl()
        {
            return "~/EPiServer.Research.Wiki/Units/Feed.ascx";
        }
    }

   
}